package com.cn.servlet;

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.cn.domain.User;
import com.cn.service.UserService;
import com.cn.service.impl.UserServiceImpl;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	
	private UserService userService=new UserServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//使用map获取登陆页面的用户信息
		Map<String,String[]> map=req.getParameterMap();
		//获取验证码
		String veryCode=req.getParameter("veryCode");
		//先验证验证码
		String validateCode=(String) req.getSession().getAttribute("validateCode");
		//System.out.println("validateCode="+validateCode);
		if(validateCode.equals(veryCode)) {
			//验证码对了开始注册
			try {
				User user=new User();
				//将登陆页面输入的信息封装user
				BeanUtils.populate(user, map);
				user.setHu_status("1");
				if(userService.addUser(user)>0) {
					//System.out.println("插入成功!");
					req.getRequestDispatcher("/reg-result.jsp").forward(req, resp);
				}else {
					req.setAttribute("info", "用户注册失败!");
					req.getRequestDispatcher("/error.jsp").forward(req, resp);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else {
			//验证码存在不能注册
			req.setAttribute("info", "用户注册失败!");
			req.getRequestDispatcher("/error.jsp").forward(req, resp);
		}
	}
}
